package configuration

import (
	"encoding/json"
	"fmt"
	"kop/modules/configuration/client"
	"kop/util/log"
	"math/rand"
)

func init() {

	var err error
	var b = client.Load("DateTemplate")

	if err = json.Unmarshal(b, &DateConfigs); err != nil {
		panic(err)
	}

	log.Info("Load DateTemplate.json success.")

	b = client.Load("DateAwardBag")
	if err = json.Unmarshal(b, &DateAwardConfigs); err != nil {
		panic(err)
	}

	log.Info("Load DateAwardBag.json success.")

}

type (
	// 约会
	DateConfig struct {
		ID          int32   // 索引ID
		DateID      int32   // 约会ID
		PlaceID     int32   // 地点ID
		DateDialogs []int32 // 问题ID
	}

	// 约会奖励
	DateAwardConf struct {
		ID         int32 // 索引
		AwardBagID int32 // 奖励包ID
		Weight     int32 // 权重
		AwardType  int32 // 奖励类型
		Value      int32 // 奖励参数
		CountMin   int32 // 最小数量
		CountMax   int32 // 最大数量
	}
)

func (c DateAwardConf) RandN() int32 {

	if c.CountMin == c.CountMax {
		return c.CountMax
	}

	return c.CountMin + rand.Int31n(c.CountMax-c.CountMin+1)
}

var (
	DateConfigs      = map[int32]DateConfig{}
	DateAwardConfigs = map[int32]DateAwardConf{}
)

func GetByDateIDPlaceID(dateID, placeID int32) (DateConfig, error) {

	for _, conf := range DateConfigs {
		if conf.DateID == dateID && conf.PlaceID == placeID {
			return conf, nil
		}
	}

	return DateConfig{}, fmt.Errorf("DateID+PlaceID not found [%d]+[%d]", dateID, placeID)
}

func GetByDateAwardType(Type int32) []DateAwardConf {

	var res []DateAwardConf

	for _, conf := range DateAwardConfigs {
		if conf.AwardBagID == Type {
			res = append(res, conf)
		}
	}

	if len(res) == 0 {
		panic(fmt.Errorf("DateAwardType not found [%d]", Type))
	}

	return res
}
